package com.tencent.wxcloudrun.frontcontroller;

import com.alibaba.fastjson.JSONObject;
import com.tencent.wxcloudrun.dto.*;
import com.tencent.wxcloudrun.mapper.GoodsMapper;
import com.tencent.wxcloudrun.service.OrderService;
import com.tencent.wxcloudrun.service.OrdergoodsService;
import com.tencent.wxcloudrun.service.UsercouponService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.tencent.wxcloudrun.uitls.JwtTokenUtils.*;

/**
 * @author lichongbing
 * @version 1.0.0
 * @createdate 2023/3/4 18:29
 * @description: TODO
 */
@RestController
@Api(tags = "订单模块")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrdergoodsService ordergoodsService;

    @Autowired
    private UsercouponService usercouponService;

    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 确认收货
     */
    @Operation(summary = "微信小程序确认收货免code")
    @PostMapping(value = "/wxcloud/orderDelivery")
    Response orderDelivery(HttpServletRequest request, @RequestBody OrderDetailRequest json) {

        return null;
    }


    @Operation(summary = "微信小程序获取订单详情免code")
    @PostMapping(value = "/wxcloud/orderDetail")
    OrderDetailResponse orderDetail(HttpServletRequest request, @RequestBody OrderDetailRequest json) {
        // 对订单号做判断就行
        /**
         * hxNumber	核销码	query	false
         * string
         * id	订单id	query	false
         * string
         * orderNumber	订单号	query	false
         * string
         * peisongOrderId	配送订单id
         */
        String openid = request.getHeader("X-WX-OPENID");
        String orderId = json.getOrderId();

        Order order = orderService.orderDetail(orderId);
        OrderDetailResponse orderDetailResponse = new OrderDetailResponse();
        OrderInfo orderInfo = new OrderInfo();
        OrderInfos orderInfos = new OrderInfos();
        // orderInfos.setShopIdZt(order.getShopidzt());
        // orderInfos.setHxNumber(order.getHxnumber());
        orderInfos.setStatus(order.getStatus());
        //orderInfos.setIsNeedLogistics(order.getIsneedlogistics());
        orderInfos.setQudanhao(order.getQudanhao());
        //orderInfos.setDateClose(order.getDateclose());
        orderInfos.setDateAdd(order.getDateadd());
        orderInfos.setAmountReal(order.getAmountreal());
        orderInfo.setOrderInfo(orderInfos);
        Logistics logistics = new Logistics();
        logistics.setAddress("广东省深圳市南山区");
        logistics.setMobile("18888888888");
        logistics.setLinkMan("张三");
        logistics.setNeedLogistics(true);
        logistics.setQudanhao(1);
        orderInfo.setLogistics(logistics);
        List<Goods> goodsList = goodsMapper.goodsList(orderId);
        orderInfo.setGoods(goodsList);
        orderDetailResponse.setData(orderInfo);
        orderDetailResponse.setMsg("success");
        orderDetailResponse.setCode(0);
        return orderDetailResponse;
    }

    /**
     * 订单核销
     */
    @Operation(summary = "微信小程序订单核销免code")
    @PostMapping(value = "/wxcloud/orderHXV2")
    ResponseBase orderHXV2(HttpServletRequest request, @RequestBody OrderDetailRequest json) {

        return null;
    }

    @Operation(summary = "微信小程序订单列表免code")
    @PostMapping(value = "/wxcloud/orderList")
    OrderListResponse orderList(HttpServletRequest request) {
        String openid = request.getHeader("X-WX-OPENID");
        Map<String, List<Ordergoods>> goodsMap = new HashMap<>();
        List<Order> orderList = orderService.orderList(openid);
        for (int i = 0; i < orderList.size(); i++) {
            String id = orderList.get(i).getId();
            List<Ordergoods> ordergoodsList = ordergoodsService.ordergoodsList(id);
            goodsMap.put(id, ordergoodsList);
        }
        OrderListResponse orderListResponse = new OrderListResponse();
        OrderList orderList1 = new OrderList();
        orderList1.setOrderList(orderList);
        orderList1.setGoodsMap(goodsMap);
        orderListResponse.setData(orderList1);
        return orderListResponse;
    }

    /**
     * 扫码点餐下单
     */
    @Operation(summary = "扫码点餐下单")
    @PostMapping("/wxcloud/cyTableAddOrder")
    CyTableAddOrderResponse cyTableAddOrder(HttpServletRequest request, @RequestBody List<CyTableAddOrderRequest> json) {
        log.info(json.toString());
        String openid = request.getHeader("X-WX-OPENID");
        String token = request.getHeader("token");
        boolean expiration = isExpiration(token);
        if (expiration) {
            CyTableAddOrderResponse cyTableAddOrderResponse = new CyTableAddOrderResponse();
            cyTableAddOrderResponse.setData("");
            cyTableAddOrderResponse.setCode(1);
            cyTableAddOrderResponse.setMsg("token过期");
            return cyTableAddOrderResponse;
        } else {
            String orderId = getOrderIdByTime();
            String tableId = getTableId(token);
            String key = getKey(token);
            //添加订单
            orderService.cyTableAddOrder(orderId, openid, tableId, key);
            for (int i = 0; i < json.size(); i++) {
                CyTableAddOrderRequest cyTableAddOrderRequest = json.get(i);
                Integer goodsId = cyTableAddOrderRequest.getGoodsId();
                Integer number = cyTableAddOrderRequest.getNumber();
                String propertyChildIds = cyTableAddOrderRequest.getPropertyChildIds();
                orderService.addOrderGoods(orderId, goodsId, number, propertyChildIds);
            }
            CyTableAddOrderResponse cyTableAddOrderResponse = new CyTableAddOrderResponse();
            cyTableAddOrderResponse.setData("");
            cyTableAddOrderResponse.setCode(0);
            cyTableAddOrderResponse.setMsg("success");
            return cyTableAddOrderResponse;
        }


    }

    //生成订单号22位
    private String getOrderIdByTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 3; i++) {
            result += random.nextInt(10);
        }
        return newDate + result;
    }

    /**
     * 关闭订单
     */
    @Operation(summary = "关闭订单")
    @PostMapping("/wxcloud/orderClose")
    OrderCloseResponse orderClose(HttpServletRequest request, @RequestBody OrderCloseRequest json) {
        return null;
    }


    /**
     * 钱包支付订单
     */
    @Operation(summary = "钱包支付订单")
    @PostMapping("/wxcloud/orderPay")
    OrderPayResponse orderPay(HttpServletRequest request, @RequestBody OrderPayRequest json) {
        return null;
    }

    @Operation(summary = "删除订单")
    @PostMapping("/wxcloud/orderDelete")
    OrderDeleteResponse orderDelete(HttpServletRequest request, @RequestBody OrderDeleteRequest json) {
        return null;
    }

    /**
     * 在线买单-优惠买单
     */
    @Operation(summary = "在线买单-优惠买单")
    @PostMapping("/wxcloud/payBill")
    PayBillResponse payBill(HttpServletRequest request, @RequestBody PayBillRequest json) {
        return null;
    }


    /**
     * 创建订单[下单]
     */
    @Operation(summary = "创建订单[下单]")
    @PostMapping("/wxcloud/orderCreate")
    JSONObject orderCreate(HttpServletRequest request, @RequestBody OrderCreateRequest json) {
        JSONObject jsonObject = new JSONObject();
        String openid = request.getHeader("X-WX-OPENID");
        String orderid = orderService.addOder(openid, json);
        //获取订单商品数量
        Integer goodsNumber = orderService.getOrderGoodsNumber(orderid).get("goodsNumber");
        //获取订单总金额
        Integer amountTotle = orderService.getOrderGoodsNumber(orderid).get("amountTotle");
        //获取订单优惠券
        List<Usercoupons> couponUserList = usercouponService.getCouponUserList(openid);
        jsonObject.put("code", 0);
        jsonObject.put("message", "OK");
        JSONObject data = new JSONObject();
        data.put("orderId", orderid);
        //订单id
        //积分抵扣数量
        data.put("score", 1);
        //商品数量
        data.put("goodsNumber", goodsNumber);
        //订单总金额
        data.put("amountTotle", amountTotle);
        //优惠券列表
        data.put("couponUserList", couponUserList);
        //配送费
        data.put("amountLogistics", goodsNumber);
        //实际支付价格
        data.put("amountReal", amountTotle * goodsNumber);
        jsonObject.put("data", data);
        return jsonObject;

    }

    @PostMapping("/wxcloud/orderCreate1")
    public String getString(@RequestBody OrderCreateRequest json) {
        log.info(json.toString());
        return "{\n" +
                "  \"code\": 0,\n" +
                "  \"message\": \"OK\",\n" +
                "  \"data\": {\n" +
                "    \"score\": 1,\n" +
                "    \"goodsNumber\": \"test\",\n" +
                "    \"amountTotle\": 1,\n" +
                "    \"couponUserList\": [\n" +
                "      {\n" +
                "        \"moneyType\": 1,\n" +
                "        \"moneyHreshold\": 1,\n" +
                "        \"name\": \"满100减10\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"moneyType\": 2,\n" +
                "        \"moneyHreshold\": 2,\n" +
                "        \"name\": \"满200减30\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"moneyType\": 3,\n" +
                "        \"moneyHreshold\": 3,\n" +
                "        \"name\": \"满300减50\"\n" +
                "      }\n" +
                "    ],\n" +
                "    \"amountLogistics\": 0.9,\n" +
                "    \"amountReal\": 0.1\n" +
                "  }\n" +
                "}\n";
    }

}
